package cn.pengpeng.day04.avg;

import java.io.File;
import java.io.IOException;

import org.apache.commons.io.FileUtils;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.DoubleWritable;
import org.apache.hadoop.io.IntWritable;
import org.apache.hadoop.io.LongWritable;
import org.apache.hadoop.io.Text;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.codehaus.jackson.JsonNode;
import org.codehaus.jackson.map.ObjectMapper;


public class UserMoveAvg {
	public static class MapTask extends Mapper<LongWritable, Text, Text, IntWritable>{
		@Override
		protected void map(LongWritable key, Text value, Mapper<LongWritable, Text, Text, IntWritable>.Context context)
				throws IOException, InterruptedException {
			//{"movie":"1193","rate":"5","timeStamp":"978300760","uid":"1"}
			ObjectMapper mapper = new ObjectMapper();
			JsonNode tree = mapper.readTree(value.toString());
			String uid = tree.get("uid").asText();
			int rate = Integer.parseInt(tree.get("rate").asText());
			context.write(new Text(uid), new IntWritable(rate));
		}
	}
	
	public static class ReduceTask extends Reducer<Text, IntWritable, Text, DoubleWritable>{
		@Override
		protected void reduce(Text uid, Iterable<IntWritable> rates,
				Reducer<Text, IntWritable, Text, DoubleWritable>.Context context)
				throws IOException, InterruptedException {
			long sum = 0;
			long count = 0;
			for (IntWritable rate : rates) {
				sum+=rate.get();
				count++;
			}
			double avg = sum*1.0/count;
			context.write(uid, new DoubleWritable(avg));
		}
	}
	
	public static void main(String[] args) throws Exception {
		Configuration conf = new Configuration();
		Job job = Job.getInstance(conf);
		
		//设置job的map 和 reduce 是哪一个 提交任务的类
		job.setMapperClass(MapTask.class);
		job.setReducerClass(ReduceTask.class);
		job.setJarByClass(UserMoveAvg.class);
		
		//设置输出的类型
		job.setMapOutputKeyClass(Text.class);
		job.setMapOutputValueClass(IntWritable.class);
		
		job.setOutputKeyClass(Text.class);
		job.setOutputValueClass(IntWritable.class);
		
		job.setNumReduceTasks(2);
		//设置输入目录和输出目录
		FileInputFormat.addInputPath(job, new Path("d:/data/rating.json"));
		FileOutputFormat.setOutputPath(job, new Path("d:/out/avgoutput"));
		
		
		File file = new File("d:/out/avgoutput");
		if(file.exists()){
			FileUtils.deleteDirectory(file);
		}
		
		//提交任务并等待任务结束，能够打印日志
		boolean waitForCompletion = job.waitForCompletion(true);
		System.out.println(waitForCompletion?"程序正常退出":"程序有问题了");
	}

}
